package com.yu.yupicture.manger.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.yu.yupicture.Untils.ThrowUntil;
import com.yu.yupicture.exception.ErrorCode;
import com.yu.yupicture.exception.biusnessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;


/**
 * 通过url上传图片工具类
 */
@Slf4j
@Service
public class urlUntil extends CommenUpliadUntil {

    final List<String> allowSuffix = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");

    /**
     * 校验参数
     *
     * @param
     */
    @Override
    public void validateFile(Object input) {
        String url = (String) input;
        ThrowUntil.throwIf(url == null, ErrorCode.PARAMS_ERROR, "url不能为空");

        //1:校验url格式
        try {
            new URL(url);
        } catch (MalformedURLException e) {
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "url格式错误");
        }
        //2:发送head请求,判断文件是否存在
        HttpResponse response = null;
        try {
            response = HttpUtil.createGet(url).execute();
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            //3：判断文件类型
            String context = response.header("Content-Type");
            if (context == null || !allowSuffix.contains(context.toLowerCase())) {
                throw new biusnessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
            try {
                //4:校验文件大小
                String header = response.header("Content-Length");
                if (header == null || Integer.parseInt(header) > 6 * 1024 * 1024) {
                    throw new biusnessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过6MB");
                }
            } catch (NumberFormatException e) {
                throw new biusnessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
            }
        } catch (Exception e) {
            log.error("文件错误", e);
            throw new biusnessException(ErrorCode.PARAMS_ERROR, "文件错误");
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    /**
     * 获取文件原始名
     *
     * @param input
     * @return
     */
    @Override
    public String getFileName(Object input) {
        String fileUrl = (String) input;
        return FileUtil.getName(fileUrl)+".jpg";
    }

    /**
     * 处理文件来源
     *
     * @param input
     * @param file
     */
    @Override
    public void createTempFile(Object input, File file) {
        String url = (String) input;
        ThrowUntil.throwIf(url == null, ErrorCode.PARAMS_ERROR, "url不能为空");
        log.info("url文件路径：" + url);
        HttpUtil.downloadFile(url, file);
    }
}



